package com.xmh.security_1.service.impl;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.xmh.security_1.dao.RolesDAO;
import com.xmh.security_1.dao.RolesUserDAO;
import com.xmh.security_1.entity.RolesEntity;
import com.xmh.security_1.entity.RolesUserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.xmh.security_1.dao.UserDAO;
import com.xmh.security_1.entity.UserEntity;
import com.xmh.security_1.service.UserService;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO dao;

    @Autowired
    private RolesUserDAO rolesUserDAO;

    @Autowired
    private RolesDAO rolesDAO;

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public Map<String, Object> add(UserEntity user) {
        dao.add(user);
        return successMessages();
    }

    @Override
    public Map<String, Object> delete(UserEntity user) {
        dao.delete(user);
        return successMessages();
    }

    @Override
    public Map<String, Object> update(UserEntity user) {
        dao.update(user);
        return successMessages();
    }

    @Override
    public List<UserEntity> selectList(Map<String, Object> jsonMap) {
        return dao.selectList(jsonMap);
    }

    @Override
    public UserEntity get(UserEntity user) {
        return dao.get(user);
    }

    /**
     * 返回成功提示
     *
     * @return
     */
    private Map<String, Object> successMessages() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "200");
        map.put("msg", "成功");
        return map;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(s)) {
            return new UserEntity();
        }

        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(s);
        UserEntity user = dao.get(userEntity);
        if (user == null) {
            //避免返回null，这里返回一个不含有任何值的User对象，在后期的密码比对过程中一样会验证失败
//            return new UserEntity();
            throw new RuntimeException("账号密码有误");
        }

        RolesUserEntity rolesUserEntity = new RolesUserEntity();
        rolesUserEntity.setUid(user.getId());
        List<RolesUserEntity> list = rolesUserDAO.selectList(rolesUserEntity.toMap());

        //查询用户的角色信息，并返回存入user中
        List<RolesEntity> roles = new ArrayList<>();

        for (RolesUserEntity roleuser : list) {
            roles.add(rolesDAO.getById(roleuser.getRid()));
        }
        user.setRolesEntityList(roles);

        return user;
    }
}
